﻿using OrBitDataModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Windows.Forms;
using OrBitDataModule.Base;
using System.Net.Sockets;
using System.Reflection.Emit;
using OrBitDataModule.Common;
using OrBitDataModule.Models;
using Newtonsoft.Json;
using System.Runtime.Remoting.Messaging;
using System.Windows.Documents;

namespace OrBitDataModule.Contract
{
    public static class TaskApi
    {

        /// <summary>
        /// 通过WebApi新增项目
        /// </summary>
        /// <param name="taskName"></param>
        /// <param name="protocol"></param>
        /// <param name="taskSetting"></param>
        /// <param name="scriptName"></param>
        /// <param name="apiName"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static async Task<(bool Result, string Message)> AddTask(string uniqueId, string taskName, string protocol, string taskDescription, string taskSetting, string dataProtocolScriptId, string webApiName, string userName, string password)
        {
            string operateApiName = "DataProtocol";
            var tokenResult = await WebApi.GetAccessTokenAsync(operateApiName, SharedData.LoginUserName, SharedData.LoginUserPassword);
            if (tokenResult.Result)
            {
                string token = tokenResult.Token;
                var (_, Response) = await WebApi.HttpPostAsync(operateApiName, token, new
                {
                    OperateType = "Add",
                    DataProtocolId = uniqueId,
                    ProtocolName = taskName,
                    ProtocolType = protocol,
                    ProtocolDescription = taskDescription,
                    ProtocolSetting = taskSetting,
                    DataProtocolScriptId = dataProtocolScriptId,
                    WebApiName = webApiName,
                    ApiUserName = userName,
                    ApiPassword = EncryptionHelper.Encode(password)
                });
                JObject obj = JObject.Parse(Response);
                bool result = obj["IsSuccess"].Value<bool>();
                string message = obj["ReturnMessage"].Value<string>();
                return (result, message);
            }
            return (false, tokenResult.Message);
        }

        public static async Task<(bool Result, string Message)> RemoveTask(string uniqueId)
        {
            string operateApiName = "DataProtocol";
            var tokenResult = await WebApi.GetAccessTokenAsync(operateApiName, SharedData.LoginUserName, SharedData.LoginUserPassword);
            if (tokenResult.Result)
            {
                string token = tokenResult.Token;
                var (_, Response) = await WebApi.HttpPostAsync(operateApiName, token, new
                {
                    OperateType = "Delete",
                    DataProtocolId = uniqueId
                });
                JObject obj = JObject.Parse(Response);
                bool result = obj["IsSuccess"].Value<bool>();
                string message = obj["ReturnMessage"].Value<string>();
                return (result, message);
            }
            return (false, tokenResult.Message);
        }

        /// <summary>
        /// 获取所有的任务
        /// </summary>
        /// <returns></returns>
        public static async Task<(DataProtocol Protocol, string Message)> GetAllTaskAsync()
        {
            string operateApiName = "DataProtocol";
            var tokenResult = await WebApi.GetAccessTokenAsync(operateApiName, SharedData.LoginUserName, SharedData.LoginUserPassword);
            if (tokenResult.Result)
            {
                string token = tokenResult.Token;
                var (_, Response) = await WebApi.HttpPostAsync(operateApiName, token, new { OperateType = "GetAll" });
                DataProtocol dataProtocol = JsonConvert.DeserializeObject<DataProtocol>(Response);
                return (dataProtocol, string.Empty);
            }
            return (null, tokenResult.Message);
        }


        /// <summary>
        /// 获取所有的任务
        /// </summary>
        /// <returns></returns>
        public static async Task<List<string>> GetAllWebApiList()
        {
            string operateApiName = "DataProtocol";
            List<string> list = new List<string>();
            var tokenResult = await WebApi.GetAccessTokenAsync(operateApiName, SharedData.LoginUserName, SharedData.LoginUserPassword);
            if (tokenResult.Result)
            {
                string token = tokenResult.Token;
                var (_, Response) = await WebApi.HttpPostAsync(operateApiName, token, new { OperateType = "GetWebApi" });

                JObject jsonObject = JObject.Parse(Response);
                JArray dataArray = (JArray)jsonObject["Data"];
                foreach (JObject item in dataArray)
                {
                    string apiName = item.Value<string>("ApiName");
                    list.Add(apiName);
                }
            }
            return list;
        }
        /// <summary>
        /// 获取所有任务
        /// </summary>
        /// <returns></returns>
        public static async Task<(bool Result, List<TaskModel> TaskList)> GetAllTask()
        {
            List<TaskModel> list = new List<TaskModel>();
            var result = await TaskApi.GetAllTaskAsync();
            if (result.Protocol != null)
            {
                foreach (var item in result.Protocol.Data)
                {
                    if (!list.Any(a => a.UniqueId.Equals(item.DataProtocolId)))
                    {
                        list.Add
                       (
                           new TaskModel()
                           {
                               UniqueId = item.DataProtocolId,
                               Status = TaskRunningStatus.Stoped,
                               TaskName = item.ProtocolName,
                               TaskType = item.ProtocolType,
                               ProtocolSetting = item.ProtocolSetting,
                               DataProtocolScriptId = item.DataProtocolScriptId,
                               ScriptName = item.ScriptName,
                               ApiName = item.ApiName,
                               ApiUserName = item.ApiUserName,
                               ApiPassword = item.ApiPassword,
                               DataTask = null
                           }
                        );
                    }
                }
                return (true, list);
            }
            else
            {
                return (false, list);
            }
        }

        /// <summary>
        /// 获取单个任务
        /// </summary>
        /// <returns></returns>
        public static async Task<(bool Result, TaskModel TaskModel, string Message)> GetTaskById(string uniqueId)
        {
            string operateApiName = "DataProtocol";
            var tokenResult = await WebApi.GetAccessTokenAsync(operateApiName, SharedData.LoginUserName, SharedData.LoginUserPassword);
            if (tokenResult.Result)
            {
                string token = tokenResult.Token;
                var (_, Response) = await WebApi.HttpPostAsync(operateApiName, token, new { OperateType = "Get", DataProtocolId = uniqueId });
                JObject obj = JObject.Parse(Response);
                bool result = obj["IsSuccess"].Value<bool>();
                string message = obj["ReturnMessage"].Value<string>();
                if (result)
                {
                    JArray dataArray = (JArray)obj["Data"];
                    foreach (JObject item in dataArray)
                    {
                        TaskModel taskModel = new TaskModel()
                        {
                            UniqueId = item.Value<string>("DataProtocolId"),
                            Status = TaskRunningStatus.Stoped,
                            TaskName = item.Value<string>("ProtocolName"),
                            TaskType = item.Value<string>("ProtocolType"),
                            TaskDescription = item.Value<string>("ProtocolDescription"),
                            ProtocolSetting = item.Value<string>("ProtocolSetting"),
                            DataProtocolScriptId = item.Value<string>("DataProtocolScriptId"),
                            ScriptName = item.Value<string>("ScriptName"),
                            ApiName = item.Value<string>("ApiName"),
                            ApiUserName = item.Value<string>("ApiUserName"),
                            ApiPassword = EncryptionHelper.Decode(item.Value<string>("ApiPassword")),
                            DataTask = null
                        };
                        return (true, taskModel, string.Empty);
                    }
                }
                return (false, null, message);
            }
            return (false, null, tokenResult.Message);
        }
    }
}
